// 云函数入口文件
const cloud = require('wx-server-sdk')

// 初始化云开发
cloud.init({
  env: 'liucheng-2gmqvcgs50e86304' // 使用指定的云环境
});

// 云函数入口函数
exports.main = async (event, context) => {
  const db = cloud.database()
  const _ = db.command

  try {
    console.log('Fetching user records from User table')

    // 获取 User 表中的所有记录，仅获取 username 字段
    const usersRes = await db.collection('User').field({
      username: true
    }).get()

    // 检查是否找到用户记录
    if (usersRes.data.length === 0) {
      console.warn('No users found')
      return {
        success: false,
        message: 'No users found'
      }
    }

    console.log('User records fetched successfully:', usersRes.data)

    // 获取所有用户的用户名
    const userNames = usersRes.data.map(user => user.username)
    console.log('Extracted user names:', userNames)

    // 初始化返回结果
    let result = []

    // 遍历每个用户的用户名，查询对应的订单数量
    for (let username of userNames) {
      if (!username) {
        console.warn('Skipping user with undefined username')
        continue
      }

      console.log('Fetching order count for user:', username)

      // 查询 Order 表中 username 字段与当前用户用户名匹配的记录数量
      const ordersRes = await db.collection('Order').where({
        user: username
      }).count()

      console.log(`Order count for user ${username}:`, ordersRes.total)

      // 将结果添加到返回结果中
      result.push({
        username: username,
        orderCount: ordersRes.total
      })
    }

    console.log('Final result:', result)

    // 返回成功结果
    return {
      success: true,
      data: result
    }
  } catch (error) {
    console.error('Error occurred:', error.message)
    // 返回错误结果
    return {
      success: false,
      message: 'Error: ' + error.message
    }
  }
}
